﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace JwtDemoServer.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly ILogger<AuthenticationController> _logger;
        private readonly IConfiguration _configuration;

        public AuthenticationController(ILogger<AuthenticationController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        [HttpPost]
        public string Login()
        {
            var claims = new[]
            {
               new Claim(ClaimTypes.Name, "TestUser1"),
               new Claim("Role","Administrator"),//自定义类型的Claim
               new Claim(ClaimTypes.Role,"ClaimRole"),//默认的ClaimTypes
            };

            return CreateAccessToken(claims, _configuration);
        }

        private string CreateAccessToken(IEnumerable<Claim> claims, IConfiguration configuration, TimeSpan? expiration = null)
        {
            var now = DateTime.UtcNow;

            var SecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"]));

            var jwtSecurityToken = new JwtSecurityToken(
                issuer: configuration["Authentication:JwtBearer:Issuer"],
                audience: configuration["Authentication:JwtBearer:Audience"],
                claims: claims,
                notBefore: now,
                expires: now.Add(expiration ?? TimeSpan.FromSeconds(configuration.GetValue<long>("Authentication:JwtBearer:Expiration"))),
                signingCredentials: new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256)
            );

            return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        }
    }
}